package com.cz.czchat;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.R;
import com.cz.db.DemoDBManager;
import com.cz.utils.Config;
import com.cz.utils.Utils;
import com.cz.widget.DemoHelper;
import com.cz.widget.ProgramDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

public class LoginActivity extends AppCompatActivity {
    private View mView;

    private EditText userNameText;
    private EditText passwordText;
    private Button loginButton;
    private TextView registerTextView;
    private boolean autoLogin = false;
    private ProgramDialog programDialog;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case Config.LOGIN_STATE_SUCCESS:
                    //Utils.closeLoadingDialog();

                    programDialog.dismiss();

                    Intent intent = new Intent(LoginActivity.this,TabActivity.class);
                    startActivity(intent);
                    LoginActivity.this.finish();
                    break;
                case Config.LOGIN_STATE_FAIL:
                    //Utils.closeLoadingDialog();
                    programDialog.dismiss();
                    String str = (String) msg.obj;
                    Toast.makeText(LoginActivity.this,"登录失败，请检查", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (DemoHelper.getInstance().isLoggedIn()) {
            autoLogin = true;
            startActivity(new Intent(LoginActivity.this, TabActivity.class));
            return;
        }

        setContentView(R.layout.activity_login);
        initView();

    }

    private void initView() {
        //沉侵式状态栏
        mView = findViewById(R.id.view);
        int result = 0;
        int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = this.getResources().getDimensionPixelSize(resourceId);
        }
        int stateHigh = 0;

        if (Utils.hasNotchAtHuawei(this)) {
            stateHigh = Utils.getNotchSizeAtHuawei(LoginActivity.this)[1];
        }
        if (Utils.hasNotchAtOPPO(LoginActivity.this)) {
            stateHigh = 80;
        }
        if (Utils.hasNotchAtVivo(LoginActivity.this)) {
            stateHigh = Utils.dip2px(LoginActivity.this, 27);
        }
        if (Utils.hasNotchAtMI(LoginActivity.this)) {
            stateHigh = 89;
        }

        if (stateHigh > result) {
            result = stateHigh;
        }
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, result);
        mView.setBackgroundColor(Color.parseColor("#eff2f6"));
        mView.setLayoutParams(params);
        Utils.translucentStatusBar(LoginActivity.this, true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }


        userNameText = findViewById(R.id.username);
        passwordText = findViewById(R.id.password);
        loginButton = findViewById(R.id.login_btn);
        registerTextView = findViewById(R.id.register_btn);

        programDialog = new ProgramDialog(LoginActivity.this);

        registerTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(userNameText.getText().toString())&& !TextUtils.isEmpty(passwordText.getText().toString())) {
                    Login(userNameText.getText().toString(),passwordText.getText().toString());
                    //Utils.showLoadingDialog(LoginActivity.this,"正在登录",false);
                    programDialog.show();
                    programDialog.setTextViewValue("正在登录...");
                }else {
                    Toast.makeText(LoginActivity.this,"用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });

        if (DemoHelper.getInstance().getCurrentUsernName() != null) {
            userNameText.setText(DemoHelper.getInstance().getCurrentUsernName());
        }

    }

    private void Login(String username, String password) {

        DemoDBManager.getInstance().closeDB();

        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(username);

        EMClient.getInstance().login(username, password, new EMCallBack() {
            @Override
            public void onSuccess() {

                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();

                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(
                        ECApplication.currentUserNick.trim());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }

                // get user's info (this should be get from App's server or 3rd party service)
                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

                Message msg = new Message();
                msg.what = Config.LOGIN_STATE_SUCCESS;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(int code, String error) {
                Message msg = new Message();
                msg.what = Config.LOGIN_STATE_FAIL;
                msg.obj = error;
                handler.sendMessage(msg);
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (autoLogin){
            return;
        }
    }
}
